package com.gowants.pems.config;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class MySessionManager extends DefaultWebSessionManager {

	private static final String TOKEN = "token";

	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	public MySessionManager() {
		super();
	}

	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		try {
			String id = WebUtils.toHttp(request).getHeader(TOKEN);
			// 如果请求头中有 token 则其值为sessionId
			if (!StringUtils.isEmpty(id)) {
				request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,
						REFERENCED_SESSION_ID_SOURCE);
				request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
				request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
//				System.out.println("SessionId1=" + id);
			} else {
				// 否则按默认规则从cookie取sessionId
				id = super.getSessionId(request, response).toString();
//				System.out.println("SessionId2=" + id);
			}
			return id;
		} catch (Exception e) {
//			System.out.println("无session信息=" + e.getMessage());
			return null;
		}
	}

}